const { src,pipe,dest,series,parallel,watch } = require('gulp');
let rename = require('gulp-rename'); // 重命名
let cssmin = require('gulp-cssmin');
let sass = require('gulp-sass')(require('sass'))
let autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var babel = require('gulp-babel'); // es6转为es5
const htmlmin = require('gulp-htmlmin'); // html压缩
var browserSync = require('browser-sync');



function cleanFile(){
    // 清除构建目录dist 
    return del(['./dist/']);
}

function reduceHtml(){
    return  src('./views/*.html')
            // 压缩html
            .pipe(htmlmin({ collapseWhitespace: true }))
            .pipe(dest('./dist'))
}

function reduceJs(){
    return src('./static/js/*.js')
            .pipe(concat('all.js'))
            .pipe(babel(
                {
                    presets: ['@babel/preset-env']
                }
            ))
            .pipe( uglify())
            .pipe(dest('./dist/js/'))
            .pipe(browserSync.stream()) // 实时把结果同步给浏览器
}

function  reduceCss(){
    return src('./static/scss/*.scss') // 源目录
            .pipe(sass())
            .pipe(autoprefixer())
            .pipe(cssmin()) // 在压缩
            .pipe(rename({
                suffix: ".min"
            }))
            .pipe(dest('./dist/css/')) // 最后输送到目标目录
            .pipe(browserSync.stream()) // 实时把结果同步给浏览器
}

function watchTask(){
    // 启动一个服务器，
    browserSync.init({
        // 指定一个网站根目录
        server:"./dist"
    })
    // 并监听文件的改变自动执行相应的任务
    watch('./static/scss/*.scss',reduceCss); // 热加载
    watch('./static/js/*.js',reduceJs); // 热加载
    watch('./views/*.html',reduceHtml).on('change',browserSync.reload) // 页面刷新
}

exports.serve = parallel(reduceHtml,reduceJs,reduceCss,watchTask)
exports.build = series(cleanFile, parallel(reduceHtml,reduceCss,reduceJs))